#pragma once
#include<string>
#include<set>
#include"Common.hpp"
#include"InetAddr.hpp"
#include"Log.hpp"
using namespace LogModule;
using namespace InetAddrModule;


class Command
{
public:
    Command()
    {
        _WhiteListCommand.insert("ls");
        _WhiteListCommand.insert("pwd");
        _WhiteListCommand.insert("ls -l");
        _WhiteListCommand.insert("touch hello.txt");
        _WhiteListCommand.insert("whoami");//_WhiteListCommand.insert("");
        _WhiteListCommand.insert("who");
    }

    bool IsSafeCommand(const std::string& cmd)
    {
        auto iter = _WhiteListCommand.find(cmd);
        if(iter == _WhiteListCommand.end())
        {
            return true;
        }
        else
          return false;
    }

    std::string Excute(const std::string& cmd, InetAddr& addr)
    {
        //1、属于白名单命令
        if(!IsSafeCommand(cmd))
        {
            return std::string("无效命令");
        }
        std::string who = addr.StringAddr();
        //2、执行命令
        FILE* fp =popen(cmd.c_str(), "r");
        if(nullptr == fp)
        {
            return std::string("你要执行的命令不存在: ") + cmd;
        }
        std::string res;
        char line[1024];
        while(fgets(line, sizeof(line), fp))
        {
            res += line;
        }
        
        pclose(fp);
        std::string result = who + "execute done, result is: \n" + res;
         LOG(LogLevel::DEBUG) << result;
        return result;
    }

    ~Command(){}
private:
    std::set<std::string> _WhiteListCommand;
};
